﻿using UnityEngine;
using UnityEngine.UI;

namespace ETModel
{
	[ObjectSystem]
	public class LoadingUIProgressComponentAwakeSystem : AwakeSystem<LoadingUIProgressComponent>
	{
		public override void Awake(LoadingUIProgressComponent self) {
            Log.Debug("loadingUI初始化完成");
            self.Text = self.GetParent<UI>().GameObject.Get<GameObject>("Text").GetComponent<Text>();
            self.ProgressBar = self.GetParent<UI>().GameObject.Get<GameObject>("ProgressBar").GetComponent<RectTransform>();
        }
	}

	[ObjectSystem]
	public class LoadingUIProgressComponentStartSystem : StartSystem<LoadingUIProgressComponent>
	{
		public override void Start(LoadingUIProgressComponent self) {
            Log.Debug("loadingUI开始检测进度");
            StartAsync(self).Coroutine();
		}
		
		public async ETVoid StartAsync(LoadingUIProgressComponent self)
		{
			TimerComponent timerComponent = Game.Scene.GetComponent<TimerComponent>();
			long instanceId = self.InstanceId;
			while (true)
			{
				await timerComponent.WaitAsync(1000);

				if (self.InstanceId != instanceId)
				{
					return;
				}

				BundleDownloaderComponent bundleDownloaderComponent = Game.Scene.GetComponent<BundleDownloaderComponent>();
				if (bundleDownloaderComponent == null)
				{
					continue;
				}
				self.Text.text = $"{bundleDownloaderComponent.Progress}%";
                float width = 500f * bundleDownloaderComponent.Progress / 100;
                self.ProgressBar.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, width);
               Log.Debug("loadingUI 目前进度:"+ self.Text.text);
            }
		}
	}

    /// <summary>
    /// loadingUI里,处理进度的组件
    /// </summary>
	public class LoadingUIProgressComponent : Component
	{
		public Text Text;
        public RectTransform ProgressBar;
    }
}
